package cn.feng.thinkInJava.b3_1_多线程并发.concurrency.a21_04_02;

//: concurrency/CloseResource.java
// Interrupting a blocked task by
// closing the underlying resource.
// {RunByHand}
import java.net.*;
import java.util.concurrent.*;
import java.io.*;
import static net.mindview.util.Print.*;

/**
 * 解决这类问题,有一个略显笨拙,但是有时确实是行之有效的防范,即关闭任务在其上发生阻塞的底层资源
 */
public class CloseResource
{
	public static void main(String[] args) throws Exception
	{
		ExecutorService exec=Executors.newCachedThreadPool();
		ServerSocket server=new ServerSocket(8080);
		InputStream socketInput=new Socket("localhost",8080).getInputStream();
		exec.execute(new IOBlocked(socketInput));
		exec.execute(new IOBlocked(System.in));
		TimeUnit.MILLISECONDS.sleep(100);
		print("Shutting down all threads");
		//在shutdownNow()被调用之后以及在两个输出流上调用close()之前的延迟强调的是一旦底层资源被关闭,任务将解除阻塞,请注意,这一点很有趣,Interrupt()看起来发生在关闭Socket而不是关闭System.in的时刻
		exec.shutdownNow();
		TimeUnit.SECONDS.sleep(1);
		print("Closing "+socketInput.getClass().getName());
		socketInput.close(); // Releases blocked thread
		TimeUnit.SECONDS.sleep(1);
		print("Closing "+System.in.getClass().getName());
		System.in.close(); // Releases blocked thread
	}
} /* Output: (85% match)
Waiting for read():
Waiting for read():
Shutting down all threads
Closing java.net.SocketInputStream
Interrupted from blocked I/O
Exiting IOBlocked.run()
Closing java.io.BufferedInputStream
Exiting IOBlocked.run()
*///:~
